import {AfterViewInit, Component, ElementRef, EventEmitter, Input, OnChanges, OnDestroy, OnInit, Output, Renderer2, SimpleChanges} from '@angular/core';
import {timer} from 'rxjs';
import {ModalOptions} from './modal';

@Component({
  selector: 'ng-tools-modal',
  templateUrl: './modal.component.html',
  styleUrls: ['./modal.component.scss']
})
export class ModalComponent implements OnInit, OnDestroy {
  @Output() event = new EventEmitter<any>();
  @Input() backdrop = 'static';
  private _options: ModalOptions;
  dom: JQuery<HTMLElement>;
  id: string;

  constructor(private elementRef: ElementRef) {
    this.id = `modal-${new Date().getTime()}`;
  }

  get options(): ModalOptions {
    return this._options;
  }

  set options(value: ModalOptions) {
    this._options = value;
  }

  ngOnInit() {
    timer(0).subscribe(() => {
      this.dom = $(this.elementRef.nativeElement).find(`#${this.id}`).first();
      this.dom.on('hidden.bs.modal', () => {
        if (this.options) {
          this.options.dynamicComponent = null;
        }
      });
    });
  }


  show(options: ModalOptions) {
    this.options = options;
    this.dom.modal('show');
  }

  hide() {
    this.dom.modal('hide');
  }

  confirm() {
    this.event.emit({'name': 'confirm', 'id': this.options.id});
  }

  close() {
    this.event.emit({'name': 'close', 'id': this.options.id});
    this.hide();
  }

  ngOnDestroy(): void {
    if (this.dom) {
      this.hide();
    }
  }

}
